package cc.booku.owlbox.UnSearchPage;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.VideoPlayer.PlayerActivity;
import cc.booku.owlbox.VideoPlayer.VideoPlayerActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchListActivity extends AppCompatActivity {


    private Toolbar Toolbar;
    private TextView httpdata, fromfileurl;
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";
    private String filePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "UserData" + File.separator + "SearchOffline" + File.separator;
    private List<Search_C> search_cList = new ArrayList<Search_C>();
    private NoScrollGridView lv_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unsearch_list);

        httpdata = (TextView) findViewById(R.id.httpdata);
        fromfileurl = (TextView) findViewById(R.id.fromfileurl);
        lv_search = (NoScrollGridView) findViewById(R.id.lv_search);
        //拿到字符串
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String SearchData = bundle.getString("SearchData");

        //加载标题栏
        LoadToolbar(SearchData);
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));

        //获取数据，等待用户保存
        if (SD_searchport() != null) {
            Httpdata(SD_searchport() + SearchData, httpdata);
        } else Log.d("Thandler--12", "地址错误======" + SD_searchport());

        //显示列表
        Message msg = new Message();
        msg.what = 12;
        bundle = new Bundle();
        bundle.putString("SearchData", SearchData);  //往Bundle中存放数据
        msg.setData(bundle);//mes利用Bundle传递数据
        handler.sendMessage(msg);//用activity中的handler发送消息

    }


    public static Boolean checkUrl(String address, int waitMilliSecond) {
        try {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(waitMilliSecond);
            conn.setReadTimeout(waitMilliSecond);

            //HTTP connect
            try {
                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int code = conn.getResponseCode();
            if ((code >= 100) && (code < 400)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    //请求获取json


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 12:

                    String str9 = msg.getData().getString("SearchData");//接受msg传递过来的参数
                    fromfileurl.setText(SD_searchport() + str9);
                    //HttpResponse(SD_searchport() + str9);
                    //Log.i("response===========>",SD_searchport()+str9);
                    if (SD_searchport() != null) {
                        HttpResponse(SD_searchport() + str9);
                    } else Log.d("Thandler--12", "地址错误======" + SD_searchport());
                    break;
                case 16:
//                    String jsondata = msg.getData().getString("jsondata");//接受msg传递过来的参数
//                    searchdata.setText(jsondata);

                    SearchVideoData((ArrayList<Search_C>) search_cList);
                    break;


            }
        }
    };

    private String SD_searchport() {


        String ConfigFiles_json = FileoOperations.readAssetsTxt(SearchListActivity.this, "TxtData/ConfigFiles");
        JSONObject objsd = JSONObject.parseObject(ConfigFiles_json);
        String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
        String DecryptionAddress = Decrypt.RsaDecrypt(SearchListActivity.this, ciphertext);
        String search = objsd.getString("UNSEARCH");//推荐
        return DecryptionAddress + search;


//        //读取sd文件的json
//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//        //读取配置文件信息
//        try {
//            JSONObject obj = JSONObject.parseObject(ProfileStr);
//            String result = obj.getString("UN搜索接口");
//            String ciphertext = obj.getString("地址密文");
//            String res = Decrypt.RsaDecrypt(SearchListActivity.this,ciphertext);
//
//
//
//                    return res+result;
//
//
//        } catch (Exception e) {
//
//            Toast.makeText(SearchListActivity.this, "配置文件错误", Toast.LENGTH_SHORT).show();
////异常处理
//        }
//
//        return null;
    }

    private void LoadToolbar(String SearchData) {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        Toolbar.setTitle("结果:" + SearchData);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
//        Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
//        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_save:

                        //得到视频信息
                        //弹出框命名文件
                        //写入数据


                        Bundle bundle = getIntent().getExtras();
                        //接收name值
                        String SearchData = bundle.getString("SearchData");
                        if (!FileoOperations.fileIsExists(filePath + SearchData + ".txt")) {

                            //不存在就说明是第一个，组合成json
                            String content = httpdata.getText().toString();
                            //不存在就创建
                            FileoOperations.writeData(filePath, SearchData, content);
                            Toast.makeText(SearchListActivity.this, "离线完成", Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(SearchListActivity.this, "已经存在", Toast.LENGTH_SHORT).show();
                        }

                        break;

                }
                return true;
            }
        });
    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);//toolbar添加menu菜单
        return true;
    }

    private Search_C searchC;

    private void HttpResponse(String url) {

        search_cList.clear();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
//               // Log.i("onResponse===========>",res);
//                Message msg = new Message();
//                msg.what = 16;
//                Bundle bundle = new Bundle();
//                bundle.putString("jsondata",res);  //往Bundle中存放数据
//                // bundle.putString("text2","Time：2016-11-03");  //往Bundle中put数据
//                msg.setData(bundle);//mes利用Bundle传递数据
//                handler.sendMessage(msg);//用activity中的handler发送消息

                List<Search_C> collectionStationCList = JSON.parseArray(res, Search_C.class);
                for (Search_C normVideo : collectionStationCList) {
                    searchC = new Search_C();

//    vod_score  ---评分
//    vod_name	----影片名称
//    vod_class  ----类型
//    vod_pic ----图片地址
//    vod_play_url --视频地址
//    vod_add_time  ---添加日期

//    vod_actor ---演员
//    vod_director ---导演
//    vod_blurb  ---影片简介
//    vod_area  ---地区
//    vod_year  ---上映年份
//    vod_lang  ---语言

                    String vod_score = normVideo.getVod_score();
                    String vod_name = normVideo.getVod_name();
                    String vod_class = normVideo.getVod_class();
                    String vod_add_time = normVideo.getVod_add_time();
                    String vod_pic = normVideo.getVod_pic();
                    String vod_play_url = normVideo.getVod_play_url();

                    String vod_actor = normVideo.getVod_actor();
                    String vod_director = normVideo.getVod_director();
                    String vod_blurb = normVideo.getVod_blurb();
                    String vod_area = normVideo.getVod_area();
                    String vod_year = normVideo.getVod_year();
                    String vod_lang = normVideo.getVod_lang();
                    String vod_id = normVideo.getVod_id();

                    // Log.d("ImageviewHolder", "显示图片url======" + vod_pic);

                    searchC.setVod_score("评分:" + vod_score);
                    searchC.setVod_name(vod_name);
                    searchC.setVod_class(vod_class + "#" + vod_year + "#" + vod_area + "#" + vod_lang + "#" + vod_id);
                    searchC.setVod_add_time(vod_add_time);
                    searchC.setVod_pic(vod_pic);
                    searchC.setVod_pic_url(vod_pic);
                    searchC.setVod_play_url(vod_play_url);
                    searchC.setVod_value_add("导演：" + vod_director + "\n演员：" + vod_actor + "\n类型：" + vod_class + "\n上映地区：" + vod_area + "\n上映年份：" + vod_year + "\n语言：" + vod_lang + "\n$片名：" + vod_name + "\n剧情简介：" + vod_blurb);


                    search_cList.add(searchC);


                }
                Message msg = new Message();
                msg.what = 16;
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

    }


    private Search_A searchA;

    public void SearchVideoData(ArrayList<Search_C> search_cList) {


        searchA = new Search_A(R.layout.uncustomize_item, this, search_cList);

        lv_search.setAdapter(searchA);
        lv_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //跳转提示
                //Toast.makeText(SearchCinemaActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
                final TextView vod_class1 = (TextView) view.findViewById(R.id.vod_class);
                final TextView vod_score1 = (TextView) view.findViewById(R.id.vod_score);
                final TextView vod_name1 = (TextView) view.findViewById(R.id.vod_name);
                final TextView vod_add_time1 = (TextView) view.findViewById(R.id.vod_add_time);
                final TextView vod_play_url1 = (TextView) view.findViewById(R.id.vod_play_url);
                final TextView vod_value_add1 = (TextView) view.findViewById(R.id.vod_value_add);
                final TextView vod_pic_url1 = (TextView) view.findViewById(R.id.vod_pic_url);

                String vod_class2 = vod_class1.getText().toString();
                String vod_score2 = vod_score1.getText().toString();
                String vod_name2 = vod_name1.getText().toString();
                String vod_add_time2 = vod_add_time1.getText().toString();
                String vod_play_url2 = vod_play_url1.getText().toString();
                String vod_value_add2 = vod_value_add1.getText().toString();
                String vod_pic_url2 = vod_pic_url1.getText().toString();

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("vod_class", vod_class2);
                bundle.putString("vod_score", vod_score2);
                bundle.putString("vod_name", vod_name2);
                bundle.putString("vod_add_time", vod_add_time2);
                bundle.putString("vod_play_url", vod_play_url2);
                bundle.putString("vod_value_add", vod_value_add2);
                bundle.putString("vod_pic", vod_pic_url2);
                intent.putExtras(bundle);
                intent.setClass(SearchListActivity.this, PlayerActivity.class);
                startActivity(intent);

            }
        });


    }


    private void Httpdata(String url, final TextView textView) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);
                if (textView == null) {
                    //Mtoast40(res);//这里我是交给handler处理字符串的比如json，或者土司显示

                } else {
                    textView.setText(res);
                }

            }
        });

    }


}
